<?php

namespace services\clinic;

use common\models\base\DrugConfig;
use common\models\patient\InfusionQueue;
use common\models\patient\InfusionQueueDrug;
use services\base\DrugService;
use services\infusion\TreatmentService;
use Yii;
use common\helpers\ExcelHelper;
use common\components\Service;
use common\helpers\ArrayHelper;
use common\models\clinic\Clinic;
use common\models\clinic\UserSurplus;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\rbac\Role;
use common\models\rbac\UserRole;
use common\models\base\Project as BaseProject;
use common\models\clinic\Project;
use common\models\clinic\UserTreatment;
use yii\db\Expression;
use yii\web\HttpException;

/**
 * Class UserTreatmentService
 * @package services\clinic
 */
class UserTreatmentService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return UserTreatment|null
     */
    public function findById(int $id = 0): ?UserTreatment
    {
        return UserTreatment::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return UserTreatment|null
     */
    public function findInfo(array $condition = []): ?UserTreatment
    {
        $query = UserTreatment::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = UserTreatment::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 治疗统计【诊室】
     *
     * @param array $params
     * @return array
     */
    public function report(array $params = [])
    {
        // 治疗列表
        $traementList = $this->getClinicGroupList([
            'type' => [UserTreatment::TYPE_TREAT, UserTreatment::TYPE_ADD, UserTreatment::TYPE_REDUCE],
            'project_id' => $params['project_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
        ]);

        $return = $this->getClinicGroupListFormat($traementList, $params['project_id']);

        // 全部治疗人数
        $patientTraementList = $this->getClinicGroupPatientList([
            'type' => [UserTreatment::TYPE_TREAT],
            'project_id' => $params['project_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
        ]);
        $return['all_treament_patient_num'] = count($patientTraementList);

        return $return;
    }

    // 导出治疗统计excel
    public function reportExcel(array $params = [])
    {
        // 治疗列表
        $traementList = $this->getClinicGroupList([
            'type' => [UserTreatment::TYPE_TREAT, UserTreatment::TYPE_ADD, UserTreatment::TYPE_REDUCE],
            'project_id' => $params['project_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
        ]);

        $data = $this->getClinicGroupListFormat($traementList, $params['project_id']);
        $list = $data['list'];

        $temp = [];
        foreach ($list as $item) {

            $temp[] = [
                'clinic_project_name' => $item['clinic_project_name'], #项目
                'clinic_name' => $item['clinic_name'], #诊室
                'treament_patient_num' => $item['treament_patient_num'], #治疗人数
                'treament_patient_times_num' => $item['treament_patient_times_num'], #治疗人次
                'treament_clinic_num' => $item['treament_clinic_num'], #治疗量
                'buy_clinic_num' => $item['buy_clinic_num'],  #购买量
                'buy_patient_num' => $item['buy_patient_num'], #购买人数
                'buy_use_num' => $item['buy_use_num'],    #人均购买
                'treament_rate' => $item['treament_rate'],  #治疗频率
                'treament_use_num' => $item['treament_use_num']  #人均用量
            ];

            foreach ($item['children'] as $children) {

                $temp[] = [
                    'clinic_project_name' => $children['clinic_project_name'], #项目
                    'clinic_name' => $children['clinic_name'], #诊室
                    'treament_patient_num' => $children['treament_patient_num'], #治疗人数
                    'treament_patient_times_num' => $children['treament_patient_times_num'], #治疗人次
                    'treament_clinic_num' => $children['treament_clinic_num'], #治疗量
                    'buy_clinic_num' => $children['buy_clinic_num'],  #购买量
                    'buy_patient_num' => $children['buy_patient_num'], #购买人数
                    'buy_use_num' => $children['buy_use_num'],    #人均购买
                    'treament_rate' => $children['treament_rate'],  #治疗频率
                    'treament_use_num' => $children['treament_use_num']  #人均用量
                ];
            }
        }

        $header = ['项目', '诊室', '治疗人数', '治疗人次', '治疗量', '购买量', '购买人数', '人均购买', '治疗频率', '人均用量'];
        // 全部治疗人数
        ExcelHelper::exportExcel($header, $temp, ['clinic_project_name','clinic_name','treament_patient_num','treament_patient_times_num','treament_clinic_num',
            'buy_clinic_num','buy_patient_num','buy_use_num','treament_rate','treament_use_num']);
    }


    /**
     * 治疗统计【项目】
     *
     * @param array $params
     * @return array
     */
    public function projectReport(array $params = [])
    {
        // 治疗列表
        $traementList = $this->getProjectGroupList([
            'type' => [UserTreatment::TYPE_TREAT, UserTreatment::TYPE_ADD],
            //'project_id' => $params['project_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
        ]);

        $return = $this->getProjectGroupListFormat($traementList);

        // 全部治疗人数
        /*$patientTraementList = $this->getClinicGroupPatientList([
            'type' => [UserTreatment::TYPE_TREAT],
            'project_id' => $params['project_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
        ]);
        $return['all_treament_patient_num'] = count($patientTraementList);*/

        return $return;
    }

    /**
     * 获取分组信息
     *
     * @param array $params
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getClinicGroupList(array $params = [])
    {
        $query = UserTreatment::find()->alias('a')
            ->select([
                'a.id',
                'a.clinic_project_id',
                'a.clinic_name',
                'a.type',
                'COUNT(a.patient_card_id) AS times_num',// 人次
                'COUNT(DISTINCT a.patient_card_id) AS patient_num',// 人数
                'SUM(a.recently_clinic_num) AS recently_clinic_num',
                'SUM(a.recently_surplus_num) AS recently_surplus_num',
                'b.name AS clinic_project_name',
                'a.clinic_sort',
                'b.sort',
            ])
            ->innerJoin(Project::tableName() . ' AS b', 'b.id = a.clinic_project_id')
            ->where([
                'a.project_id' => $params['project_id']
            ])
            ->groupBy('a.clinic_project_id, a.clinic_name, a.type');

        if (isset($params['type'])) {
            $query->andWhere(['a.type' => $params['type']]);
        }

        if (isset($params['start_time']) && $params['start_time']) {
            $query->andWhere(['>=', 'a.recently_clinic_time', strtotime($params['start_time'])]);
        }

        if (isset($params['end_time']) && $params['end_time']) {
            $query->andWhere(['<', 'a.recently_clinic_time', strtotime($params['end_time'] . ' 23:59:59')]);
        }

        return $query->asArray()->all();
    }

    /**
     * 获取治疗人数信息
     *
     * @param array $params
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getClinicGroupPatientList(array $params = [])
    {
        $query = UserTreatment::find()->alias('a')
            ->select([
                'a.patient_card_id',
            ])
            ->where([
                'a.project_id' => $params['project_id']
            ])
            ->groupBy('a.patient_card_id');

        if (isset($params['type'])) {
            $query->andWhere(['a.type' => $params['type']]);
        }

        if (isset($params['start_time']) && $params['start_time']) {
            $query->andWhere(['>=', 'a.recently_clinic_time', strtotime($params['start_time'])]);
        }

        if (isset($params['end_time']) && $params['end_time']) {
            $query->andWhere(['<', 'a.recently_clinic_time', strtotime($params['end_time'] . ' 23:59:59')]);
        }

        return $query->asArray()->all();
    }

    /**
     * 格式化统计数据
     *
     * @param array $data
     * @param int $projectId 项目ID
     * @return array
     */
    public function getClinicGroupListFormat(array $data = [], int $projectId = 0)
    {
        // 治疗项目ID
        $clinicProjectList = Yii::$app->services->clinicProject->findList([
            'select' => ['id'],
            'project_id' => $projectId,
            'template' => [Project::TEMPLATE_308, Project::TEMPLATE_NAJIN],
            'indexBy' => 'id',
        ]);

        $allTreamentPatientNum = 0;// 全部治疗人数
        $tmpTreamentPatientNum = 0;// 308治疗人数
        $tmpBuyNum = 0;// 308购买个数【非援助】
        $tmpTreamentNum = 0;// 308治疗个数

        $list = [];
        foreach ($data as $row) {
            // 操作数【治疗/购买/退费】
            $clinicNum = $row['recently_clinic_num'] + $row['recently_surplus_num'];

            // $patientArr = explode(',', $row['patient_card_id']);
            // 人次
            $patientTimesNum = $row['times_num'];

            // 人数
            $patientNum = $row['patient_num'];

            if (!isset($list[$row['clinic_project_id']])) {
                $list[$row['clinic_project_id']] = [
                    'id' => $row['clinic_project_id'] . '-0',
                    'clinic_project_name' => $row['clinic_project_name'],
                    'clinic_name' => '诊室汇总',
                    'treament_clinic_num' => 0,// 治疗量
                    'treament_patient_num' => 0,// 治疗人数
                    'treament_patient_times_num' => 0,// 治疗人次
                    'treament_rate' => 0,// 治疗频率【治疗人次/治疗人数】
                    'treament_use_num' => 0,// 人均用量【治疗量/治疗人数】
                    'buy_clinic_num' => 0,// 购买量
                    'buy_patient_num' => 0,// 购买人数
                    'buy_use_num' => 0,// 人均购买【购买量/购买人数】
                    'sort' => $row['sort'],// 治疗项目排序字段
                    'children' => [],
                ];
            }

            if (!isset($list[$row['clinic_project_id']]['children'][$row['clinic_name']])) {
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']] = [
                    'id' => $row['clinic_project_id'] . '-' . $row['id'],
                    'clinic_project_name' => $row['clinic_project_name'],
                    'clinic_name' => $row['clinic_name'],
                    'treament_clinic_num' => 0,// 治疗量
                    'treament_patient_num' => 0,// 治疗人数
                    'treament_patient_times_num' => 0,// 治疗人次
                    'treament_rate' => 0,// 治疗频率【治疗人次/治疗人数】
                    'treament_use_num' => 0,// 人均用量【治疗量/治疗人数】
                    'buy_clinic_num' => 0,// 购买量
                    'buy_patient_num' => 0,// 购买人数
                    'buy_use_num' => 0,// 人均购买【购买量/购买人数】
                    'clinic_sort' => $row['clinic_sort'],// 排序字段
                ];
            }

            if ($row['type'] == UserTreatment::TYPE_TREAT) {// 治疗
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['treament_clinic_num']
                    = $clinicNum;
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['treament_patient_num']
                    = $patientNum;
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['treament_patient_times_num']
                    = $patientTimesNum;
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['treament_rate']
                    = $patientNum ? round($patientTimesNum / $patientNum, 2) : 0;
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['treament_use_num']
                    = $patientNum ? round($clinicNum / $patientNum, 2) : 0;

                // 汇总
                $list[$row['clinic_project_id']]['treament_clinic_num']
                    += $clinicNum;
                $list[$row['clinic_project_id']]['treament_patient_num']
                    += $patientNum;
                $list[$row['clinic_project_id']]['treament_patient_times_num']
                    += $patientTimesNum;
                $list[$row['clinic_project_id']]['treament_rate']
                    = $list[$row['clinic_project_id']]['treament_patient_num'] ? round($list[$row['clinic_project_id']]['treament_patient_times_num'] / $list[$row['clinic_project_id']]['treament_patient_num'], 2) : 0;
                $list[$row['clinic_project_id']]['treament_use_num']
                    = $list[$row['clinic_project_id']]['treament_patient_num'] ? round($list[$row['clinic_project_id']]['treament_clinic_num'] / $list[$row['clinic_project_id']]['treament_patient_num'], 2) : 0;

                // 全部治疗人数
                $allTreamentPatientNum += $patientNum;
                // 308
                if (isset($clinicProjectList[$row['clinic_project_id']])) {
                    $tmpTreamentPatientNum += $patientNum;
                    $tmpTreamentNum += $clinicNum;
                }
            } elseif ($row['type'] == UserTreatment::TYPE_ADD) {// 购买
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_clinic_num']
                    += $clinicNum;
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_patient_num']
                    = $patientNum;
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_use_num']
                    = $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_patient_num'] ? round($list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_clinic_num'] / $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_patient_num'], 2) : 0;

                // 汇总
                $list[$row['clinic_project_id']]['buy_clinic_num']
                    += $clinicNum;
                $list[$row['clinic_project_id']]['buy_patient_num']
                    += $patientNum;
                $list[$row['clinic_project_id']]['buy_use_num']
                    = $list[$row['clinic_project_id']]['buy_patient_num'] ? round($list[$row['clinic_project_id']]['buy_clinic_num'] / $list[$row['clinic_project_id']]['buy_patient_num'], 2) : 0;

                // 308
                if (isset($clinicProjectList[$row['clinic_project_id']])) {
                    $tmpBuyNum += $row['recently_clinic_num'];
                }
            } else {// 退费
                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_clinic_num']
                    -= $clinicNum;

                $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_use_num']
                    = $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_patient_num'] ? round($list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_clinic_num'] / $list[$row['clinic_project_id']]['children'][$row['clinic_name']]['buy_patient_num'], 2) : 0;

                // 汇总
                $list[$row['clinic_project_id']]['buy_clinic_num']
                    -= $clinicNum;
                $list[$row['clinic_project_id']]['buy_use_num']
                    = $list[$row['clinic_project_id']]['buy_patient_num'] ? round($list[$row['clinic_project_id']]['buy_clinic_num'] / $list[$row['clinic_project_id']]['buy_patient_num'], 2) : 0;

                // 308
                if (isset($clinicProjectList[$row['clinic_project_id']])) {
                    $tmpBuyNum -= $row['recently_clinic_num'];
                }
            }
        }

        $listFormat = [];
        foreach ($list as $row) {
            $row['children'] = array_values($row['children']);
            $row['children'] = array_values(ArrayHelper::arraySort($row['children'], 'clinic_sort'));
            $listFormat[] = $row;
        }
        return [
            'all_treament_patient_num' => $allTreamentPatientNum,
            'tmp_treament_patient_num' => $tmpTreamentPatientNum,
            'tmp_buy_num' => $tmpBuyNum,
            'tmp_treament_num' => $tmpTreamentNum,
            'list' => array_values(ArrayHelper::arraySort($listFormat, 'sort'))
        ];
    }

    /**
     * 获取分组信息【项目】
     *
     * @param array $params
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getProjectGroupList(array $params = [])
    {
        $query = UserTreatment::find()->alias('a')
            ->select([
                'a.id',
                'a.clinic_project_id',
                'a.project_id',
                'a.type',
                'COUNT(a.patient_card_id) AS times_num',// 人次
                'COUNT(DISTINCT a.patient_card_id) AS patient_num',// 人数
                'SUM(a.recently_clinic_num) AS recently_clinic_num',
                'SUM(a.recently_surplus_num) AS recently_surplus_num',
                'b.name AS clinic_project_name',
                'a.clinic_sort',
                'b.sort',
                'c.name AS pname',
            ])
            ->innerJoin(Project::tableName() . ' AS b', 'b.id = a.clinic_project_id')
            ->innerJoin(BaseProject::tableName() . ' AS c', 'c.id = a.project_id')
            /*->where([
                'a.project_id' => $params['project_id']
            ])*/
            ->groupBy('a.clinic_project_id, a.project_id, a.type');

        if (isset($params['type'])) {
            $query->andWhere(['a.type' => $params['type']]);
        }

        if (isset($params['start_time']) && $params['start_time']) {
            $query->andWhere(['>=', 'a.recently_clinic_time', strtotime($params['start_time'])]);
        }

        if (isset($params['end_time']) && $params['end_time']) {
            $query->andWhere(['<', 'a.recently_clinic_time', strtotime($params['end_time'] . ' 23:59:59')]);
        }

        return $query->asArray()->all();
    }

    /**
     * 格式化统计数据【项目】
     *
     * @param array $data
     * @param int $projectId 项目ID
     * @return array
     */
    public function getProjectGroupListFormat(array $data = [])
    {
        // 治疗项目ID
        $clinicProjectList = Yii::$app->services->clinicProject->findList([
            'select' => ['id'],
//            'project_id' => $projectId,
            'template' => [Project::TEMPLATE_308, Project::TEMPLATE_NAJIN],
            'indexBy' => 'id',
        ]);

        $allTreamentPatientNum = 0;// 全部治疗人数
        $tmpTreamentPatientNum = 0;// 308治疗人数
        $tmpBuyNum = 0;// 308购买个数【非援助】
        $tmpTreamentNum = 0;// 308治疗个数

        $list = [];
        foreach ($data as $row) {
            // 操作数【治疗/购买/退费】
            $clinicNum = $row['recently_clinic_num'] + $row['recently_surplus_num'];

            // $patientArr = explode(',', $row['patient_card_id']);
            // 人次
            $patientTimesNum = $row['times_num'];

            // 人数
            $patientNum = $row['patient_num'];

            if (!isset($list[$row['clinic_project_id']])) {
                $list[$row['clinic_project_id']] = [
                    'id' => $row['clinic_project_id'] . '-0',
                    'clinic_project_name' => $row['clinic_project_name'],
                    'pname' => '医院汇总',
                    'treament_clinic_num' => 0,// 治疗量
                    'treament_patient_num' => 0,// 治疗人数
                    'treament_patient_times_num' => 0,// 治疗人次
                    'treament_rate' => 0,// 治疗频率【治疗人次/治疗人数】
                    'treament_use_num' => 0,// 人均用量【治疗量/治疗人数】
                    'buy_clinic_num' => 0,// 购买量
                    'buy_patient_num' => 0,// 购买人数
                    'buy_use_num' => 0,// 人均购买【购买量/购买人数】
                    'sort' => $row['sort'],// 治疗项目排序字段
                    'children' => [],
                ];
            }

            if (!isset($list[$row['clinic_project_id']]['children'][$row['project_id']])) {
                $list[$row['clinic_project_id']]['children'][$row['project_id']] = [
                    'id' => $row['clinic_project_id'] . '-' . $row['id'],
                    'clinic_project_name' => $row['clinic_project_name'],
                    'pname' => $row['pname'],
                    'treament_clinic_num' => 0,// 治疗量
                    'treament_patient_num' => 0,// 治疗人数
                    'treament_patient_times_num' => 0,// 治疗人次
                    'treament_rate' => 0,// 治疗频率【治疗人次/治疗人数】
                    'treament_use_num' => 0,// 人均用量【治疗量/治疗人数】
                    'buy_clinic_num' => 0,// 购买量
                    'buy_patient_num' => 0,// 购买人数
                    'buy_use_num' => 0,// 人均购买【购买量/购买人数】
                    'clinic_sort' => $row['clinic_sort'],// 排序字段
                ];
            }

            if ($row['type'] == UserTreatment::TYPE_TREAT) {// 治疗
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['treament_clinic_num']
                    = $clinicNum;
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['treament_patient_num']
                    = $patientNum;
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['treament_patient_times_num']
                    = $patientTimesNum;
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['treament_rate']
                    = round($patientTimesNum / $patientNum, 2);
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['treament_use_num']
                    = round($clinicNum / $patientNum, 2);

                // 汇总
                $list[$row['clinic_project_id']]['treament_clinic_num']
                    += $clinicNum;
                $list[$row['clinic_project_id']]['treament_patient_num']
                    += $patientNum;
                $list[$row['clinic_project_id']]['treament_patient_times_num']
                    += $patientTimesNum;
                $list[$row['clinic_project_id']]['treament_rate']
                    = round($list[$row['clinic_project_id']]['treament_patient_times_num'] / $list[$row['clinic_project_id']]['treament_patient_num'], 2);
                $list[$row['clinic_project_id']]['treament_use_num']
                    = round($list[$row['clinic_project_id']]['treament_clinic_num'] / $list[$row['clinic_project_id']]['treament_patient_num'], 2);

                // 全部治疗人数
                $allTreamentPatientNum += $patientNum;
                // 308
                if (isset($clinicProjectList[$row['clinic_project_id']])) {
                    $tmpTreamentPatientNum += $patientNum;
                    $tmpTreamentNum += $clinicNum;
                }
            } else {// 购买
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['buy_clinic_num']
                    = $clinicNum;
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['buy_patient_num']
                    = $patientNum;
                $list[$row['clinic_project_id']]['children'][$row['project_id']]['buy_use_num']
                    = round($clinicNum / $patientNum, 2);

                // 汇总
                $list[$row['clinic_project_id']]['buy_clinic_num']
                    += $clinicNum;
                $list[$row['clinic_project_id']]['buy_patient_num']
                    += $patientNum;
                $list[$row['clinic_project_id']]['buy_use_num']
                    = round($list[$row['clinic_project_id']]['buy_clinic_num'] / $list[$row['clinic_project_id']]['buy_patient_num'], 2);

                // 308
                if (isset($clinicProjectList[$row['clinic_project_id']])) {
                    $tmpBuyNum += $row['recently_clinic_num'];
                }
            }
        }

        $listFormat = [];
        foreach ($list as $row) {
            $row['children'] = array_values($row['children']);
            $row['children'] = array_values(ArrayHelper::arraySort($row['children'], 'clinic_sort'));
            $listFormat[] = $row;
        }
        return [
            'all_treament_patient_num' => $allTreamentPatientNum,
            'tmp_treament_patient_num' => $tmpTreamentPatientNum,
            'tmp_buy_num' => $tmpBuyNum,
            'tmp_treament_num' => $tmpTreamentNum,
            'list' => array_values(ArrayHelper::arraySort($listFormat, 'sort'))
        ];
    }

    /**
     * 获取患者治疗项目剩余数量
     * @param $patientCardId
     * @param int $patientId
     * @return array
     */
    public function getPatientProjectNum($patientCardId, int $patientId): array
    {
        // 治疗项目剩余列表
        $userSurplusList = UserSurplus::find()
            ->select([
                'clinic_project_id', 'clinic_project_name', 'total_num', 'help_num',
                new Expression('1 data_type'),
            ])
            ->where([
                'project_id' => Yii::$app->params['project_id'],
                'patient_card_id' => $patientCardId
            ])
            ->groupBy('clinic_project_id')
            ->orderBy(['created_at' => SORT_DESC])
            ->asArray()
            ->all();
        // 输液大厅剩余列表
        $treatmentService = new TreatmentService();
        $patientDrugSurplusList = $treatmentService->getPatientDrugSurplus($patientId);
        $patientDrugSurplusListFormat = [];
        foreach ($patientDrugSurplusList as $item) {
//            $drugTypeName = DrugConfig::$drugTypes[$item['drug_type']];
            $drugName = DrugService::getDrugContent((int)$item['drug_id'], $item['drug_name'], $item['drug_unit'], $item['drug_type'], $item['drug_volume'], $item['water_type'], $item['water_volume']);

            $item = [
                'clinic_project_id' => $item['drug_config_id'],
                'clinic_project_name' => $drugName,
                'help_num' => 0,
                'total_num' => $item['surplus_num'],
                'data_type' => 2,
            ];
            $patientDrugSurplusListFormat[] = $item;
        }
        return array_merge($userSurplusList, $patientDrugSurplusListFormat);
    }

    /**
     * 获取护士报表数据
     *
     * @param array $params
     * @return array
     * @author wangxiang
     */
    public function getNurseReportData(array $params)
    {
        $query = UserRole::find()
            ->alias('ur')
            ->leftJoin(Attr::tableName() . ' attr', 'ur.member_id = attr.member_id')
            ->leftJoin(Member::tableName() . ' m', 'm.id = attr.member_id')
            ->where([
                'ur.role_id' => Role::ID_NURSE,
                'm.status' => Member::STATUS_ENABLE,
            ]);
        // 判断当前登录者身份
        $member = Yii::$app->user->identity->member;

        if ($member->is_super == Member::IS_SUPER_NO) {
            $attr = Yii::$app->services->attr->findInfo(['member_id' => $member->id, 'project_id' => $params['project_id']]);
            if (!$attr) return [];
            if ($attr->is_department_leader == Attr::IS_DEPARTMENT_LEADER_NO) {
                $query = $query->andWhere(['attr.member_id' => $attr->member_id]);
            } else if ($attr->is_department_leader == Attr::IS_DEPARTMENT_LEADER_YES) {
                $query = $query->andWhere(['attr.department_id' => $attr->department_id]);
            }
        }

        $memberRes = $query->select(['m.id', 'm.realname'])->asArray()->all();
        $memberIdData = array_column($memberRes, 'id');

        // 治疗项目
        $res = UserTreatment::find()
            ->alias('ut')
            ->leftJoin(Project::tableName() . ' p', 'p.id = ut.clinic_project_id')
            ->where(['between', 'ut.recently_clinic_time', $params['start_date'], $params['end_date']])
            ->andWhere(['ut.operate_id' => $memberIdData, 'ut.type' => UserTreatment::TYPE_TREAT])
            ->andWhere(['!=', 'ut.clinic_project_id', 0])
            ->select(['ut.operate_id', 'ut.operate_name', 'ut.clinic_project_name', 'ut.clinic_project_id', 'ut.recently_clinic_num', 'ut.recently_surplus_num', 'p.template'])
            ->orderBy('p.sort')
            ->asArray()
            ->all();
        $data = [];
        $memberData = [];
        foreach ($memberRes as $item) {
            $memberData[$item['id']] = $item['realname'];
        }

        foreach ($res as $item) {
            // 如果治疗项目是308，则计算治疗数量， 其他的计算治疗次数
            if (Project::TEMPLATE_308 == $item['template'] || Project::TEMPLATE_NAJIN == $item['template']) {
                $num = $item['recently_clinic_num'] + $item['recently_surplus_num'];
            } else {
                $num = 1;
            }

            $data[$item['clinic_project_id']]['project'] = $item['clinic_project_name'];
            foreach ($memberIdData as $memberId) {
                !isset($data[$item['clinic_project_id']][$memberId]) && $data[$item['clinic_project_id']][$memberId] = 0;
            }
            $data[$item['clinic_project_id']][$item['operate_id']] += $num;
            $data[$item['clinic_project_id']]['total'] = isset($data[$item['clinic_project_id']]['total']) ? $data[$item['clinic_project_id']]['total'] + $num : $num;
        }
        $data = array_values($data);

        return ['list' => $data, 'member' => $memberData];
    }

    /**
     * 修复/初始化患者治疗信息表中诊室排序值
     * @author chenyuebin
     */
    public function runInit()
    {
        $clinic = Clinic::find()
            ->select(['id', 'sort'])
            ->asArray()
            ->all();
        try {
            foreach ($clinic as $val) {
                UserTreatment::updateAll(['clinic_sort' => $val['sort']], ['clinic_id' => $val['id']]);
            }
        } catch (\HttpException $exception) {
            throw new HttpException($exception->getCode(), $exception->getMessage());
        }
        return true;
    }

    /**
     * 修复治疗室ID
     */
    public function repairClinicId()
    {
        $clinicList = Clinic::find()
            ->where([
                'status' => [Clinic::STATUS_INVALID, Clinic::STATUS_ENABLE]
            ])
            ->asArray()
            ->all();

        foreach ($clinicList as $row) {
            UserTreatment::updateAll(['clinic_id' => $row['id']], ['project_id' => $row['project_id'], 'clinic_name' => $row['name']]);
        }
    }

    /**
     * 统计患者购买+治疗数量
     * @param $patientUserIds
     * @param int $drugConfigId
     * @return array
     */
    public static function getStatisticsList($patientCardIds, int $clinicProjectId): array
    {
        $res = UserTreatment::find()
            ->select([
                'patient_card_id', 'type', 'SUM(recently_clinic_num) recently_clinic_num', 'SUM(recently_surplus_num) recently_surplus_num'
            ])
            ->where([
                'project_id' => Yii::$app->params['project_id'],
                'patient_card_id' => $patientCardIds,
                'clinic_project_id' => $clinicProjectId,
            ])
            ->groupBy('patient_card_id,type')
            ->asArray()
            ->all();
        $data = [];
        foreach ($res as $row) {
            $data[$row['patient_card_id']] = $data[$row['patient_card_id']] ?? [
                'buy_num' => 0,
                'treatment_num' => 0,
            ];
            $num = $row['recently_clinic_num'] + $row['recently_surplus_num'];
            if ($row['type'] == UserTreatment::TYPE_ADD) {
                $data[$row['patient_card_id']]['buy_num'] += $num;
            } elseif ($row['type'] == UserTreatment::TYPE_TREAT) {
                $data[$row['patient_card_id']]['treatment_num'] += $num;
            } else {
                $data[$row['patient_card_id']]['buy_num'] -= $num;
            }
        }
        return $data;
    }
}
